import React, { useState } from 'react';
import axios from 'axios';
import { Button, Form, Input, Alert, Typography, notification, Spin, Card } from 'antd';
import { UserOutlined, LockOutlined, MailOutlined, CheckCircleOutlined, CloseCircleOutlined, LoadingOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { Link, useNavigate } from 'react-router-dom';
import './AuthPage.css';

const { Title, Paragraph } = Typography;

const AuthPage: React.FC = () => {
    const [isSignUp, setIsSignUp] = useState(false);
    const [error, setError] = useState('');
    const [signInForm] = Form.useForm();
    const [signUpForm] = Form.useForm();
    const [passwordValue, setPasswordValue] = useState('');
    const [confirmPasswordValue, setConfirmPasswordValue] = useState('');
    const [signInLoading, setSignInLoading] = useState(false);
    const [signUpLoading, setSignUpLoading] = useState(false);
    const [statusMessage, setStatusMessage] = useState('');
    const [statusType, setStatusType] = useState<'loading' | 'success' | 'error'>('loading');
    const navigate = useNavigate();

    // 密码验证辅助函数
    const getPasswordValidationIcon = () => {
        if (!passwordValue) return null;
        const isValid = passwordValue.length >= 8;
        return isValid ?
            <CheckCircleOutlined style={{ color: '#52c41a', fontSize: '16px' }} /> :
            <CloseCircleOutlined style={{ color: '#ff4d4f', fontSize: '16px' }} />;
    };

    const getConfirmPasswordValidationIcon = () => {
        if (!confirmPasswordValue) return null;
        const isValid = confirmPasswordValue && passwordValue === confirmPasswordValue;
        return isValid ?
            <CheckCircleOutlined style={{ color: '#52c41a', fontSize: '16px' }} /> :
            <CloseCircleOutlined style={{ color: '#ff4d4f', fontSize: '16px' }} />;
    };

    const handleSignIn = async (values: any) => {
        setError('');
        setSignInLoading(true);
        setStatusType('loading');
        setStatusMessage('正在登录，请稍候...');

        try {
            const response = await axios.post('/api/auth/login/', values);
            const { token, username } = response.data;
            if (token && username) {
                localStorage.setItem('authToken', token);
                localStorage.setItem('username', username);

                // 显示登录成功状态
                setStatusType('success');
                setStatusMessage(`登录成功！正在跳转到仪表板...`);

                // 存储用户名用于仪表盘欢迎信息
                const welcomeMsg = `欢迎回来，${username}！`;
                localStorage.setItem('welcomeMessage', welcomeMsg);
                console.log('AuthPage: 存储欢迎信息:', welcomeMsg);

                // 延迟跳转到仪表盘
                setTimeout(() => {
                    navigate('/dashboard');
                }, 1500);
            } else {
                setStatusType('error');
                setStatusMessage('登录失败，未收到有效的认证信息');
                setError('登录失败，未收到有效的认证信息。');
                setTimeout(() => {
                    setStatusMessage('');
                }, 3000);
            }
        } catch (err: any) {
            console.error('Login error:', err);
            // 提取并打印后端返回的具体错误信息
            const backendError = err.response?.data;
            console.error('Backend response:', backendError);

            let errorMessage = '登录失败，请检查您的网络连接或联系管理员。';
            // 尝试从后端响应中解析出更具体的错误信息
            if (backendError) {
                // 将后端的错误信息对象转换成一个可读的字符串
                // 例如: {"non_field_errors": ["Unable to log in..."]}
                const errorValues = Object.values(backendError).flat();
                errorMessage = errorValues.join(' ') || '用户名或密码不正确，请重试。';
            }

            setStatusType('error');
            setStatusMessage(errorMessage);
            setError(errorMessage);
            
            setTimeout(() => {
                setStatusMessage('');
            }, 5000); // 延长错误信息的显示时间
        } finally {
            setSignInLoading(false);
        }
    };

    const handleSignUp = async (values: any) => {
        setError('');
        setSignUpLoading(true);
        setStatusType('loading');
        setStatusMessage('正在注册，请稍候...');

        try {
            await axios.post('/api/auth/register/', values);

            // 显示注册成功状态
            setStatusType('success');
            setStatusMessage(`注册成功！欢迎加入智能门禁系统，${values.username}！`);

            // 显示成功通知
            notification.success({
                message: '注册成功！',
                description: `🎉 欢迎加入智能门禁系统，${values.username}！您的账户已创建成功，现在可以登录系统了。`,
                duration: 4,
                placement: 'topRight',
                icon: <CheckCircleOutlined style={{ color: '#52c41a' }} />,
            });

            // 延迟切换到登录面板
            setTimeout(() => {
                // 直接切换到登录面板并预填用户名
                setIsSignUp(false);
                signInForm.setFieldsValue({ username: values.username, password: '' });

                // 清空注册表单
                signUpForm.resetFields();
                setPasswordValue('');
                setConfirmPasswordValue('');
                setStatusMessage('');
            }, 2000);

        } catch (err: any) {
            const errorMsg = err.response?.data?.username?.[0] || '注册失败，请重试。';
            setStatusType('error');
            setStatusMessage(`注册失败：${errorMsg}`);
            setError(errorMsg);
            console.error('Registration error:', err);
            setTimeout(() => {
                setStatusMessage('');
            }, 3000);
        } finally {
            setSignUpLoading(false);
        }
    };

    return (
        <div className="auth-container">
            {/* 顶部状态提示组件 */}
            {statusMessage && (
                <div style={{
                    position: 'fixed',
                    top: '20px',
                    left: '50%',
                    transform: 'translateX(-50%)',
                    zIndex: 1000,
                    width: 'auto',
                    minWidth: '300px',
                    maxWidth: '500px'
                }}>
                    <Card
                        size="small"
                        style={{
                            background: 'rgba(255, 255, 255, 0.95)',
                            backdropFilter: 'blur(10px)',
                            border: `1px solid ${
                                statusType === 'success' ? '#52c41a' :
                                statusType === 'error' ? '#ff4d4f' : '#d9d9d9'
                            }`,
                            borderRadius: '8px',
                            boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',
                            textAlign: 'center'
                        }}
                    >
                        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '12px' }}>
                            {statusType === 'loading' && (
                                <Spin
                                    indicator={<LoadingOutlined style={{ fontSize: 16, color: '#1890ff' }} spin />}
                                />
                            )}
                            {statusType === 'success' && (
                                <CheckCircleOutlined style={{ fontSize: 16, color: '#52c41a' }} />
                            )}
                            {statusType === 'error' && (
                                <ExclamationCircleOutlined style={{ fontSize: 16, color: '#ff4d4f' }} />
                            )}
                            <span style={{
                                color: statusType === 'success' ? '#52c41a' :
                                       statusType === 'error' ? '#ff4d4f' : '#1890ff',
                                fontWeight: 500,
                                fontSize: '14px'
                            }}>
                                {statusMessage}
                            </span>
                        </div>
                    </Card>
                </div>
            )}

            <div style={{ textAlign: 'center', marginBottom: '2rem', position: 'absolute', top: '8%' }}>
                <Title level={1} style={{ color: '#333', fontSize: '2.5rem' }}>智能门禁管理系统</Title>
            </div>
            <div className={`container ${isSignUp ? 'right-panel-active' : ''}`} id="container">
                <div className="form-container sign-up-container">
                    <Form form={signUpForm} onFinish={handleSignUp} className="auth-form">
                        <Title level={2}>创建账户</Title>
                        <div style={{ margin: '15px 0' }}>
                            {/* Placeholder for social icons */}
                        </div>
                        <Form.Item
                            name="username"
                            rules={[{ required: true, message: '请输入用户名!' }]}
                            style={{ marginBottom: '16px' }}
                        >
                            <div style={{ display: 'flex', alignItems: 'center', gap: '8px', width: '100%' }}>
                                <Input
                                    size="large"
                                    prefix={<UserOutlined />}
                                    placeholder="用户名"
                                    style={{ width: 'calc(100% - 28px)' }}
                                />
                                <div style={{ width: '20px', display: 'flex', justifyContent: 'center' }}></div>
                            </div>
                        </Form.Item>
                        <Form.Item
                            name="email"
                            rules={[{ type: 'email', message: '请输入有效的邮箱地址!' }]}
                            style={{ marginBottom: '16px' }}
                        >
                            <div style={{ display: 'flex', alignItems: 'center', gap: '8px', width: '100%' }}>
                                <Input
                                    size="large"
                                    prefix={<MailOutlined />}
                                    placeholder="邮箱 (可选)"
                                    style={{ width: 'calc(100% - 28px)' }}
                                />
                                <div style={{ width: '20px', display: 'flex', justifyContent: 'center' }}></div>
                            </div>
                        </Form.Item>
                        <Form.Item
                            name="password"
                            rules={[
                                { required: true, message: '请输入密码!' },
                                { min: 8, message: '密码长度不能少于8位!' }
                            ]}
                            style={{ marginBottom: '16px' }}
                        >
                            <div style={{ display: 'flex', alignItems: 'center', gap: '8px', width: '100%' }}>
                                <Input.Password
                                    size="large"
                                    prefix={<LockOutlined />}
                                    placeholder="密码 (至少8位)"
                                    value={passwordValue}
                                    onChange={(e) => setPasswordValue(e.target.value)}
                                    style={{ width: 'calc(100% - 28px)' }}
                                />
                                <div style={{
                                    width: '20px',
                                    display: 'flex',
                                    justifyContent: 'center',
                                    alignItems: 'center'
                                }}>
                                    {getPasswordValidationIcon()}
                                </div>
                            </div>
                        </Form.Item>
                        <Form.Item
                            name="confirm"
                            dependencies={['password']}
                            rules={[
                                { required: true, message: '请确认您的密码!' },
                                ({ getFieldValue }) => ({
                                    validator(_, value) {
                                        if (!value || getFieldValue('password') === value) {
                                            return Promise.resolve();
                                        }
                                        return Promise.reject(new Error('两次输入的密码不匹配!'));
                                    },
                                }),
                            ]}
                            style={{ marginBottom: '16px' }}
                        >
                            <div style={{ display: 'flex', alignItems: 'center', gap: '8px', width: '100%' }}>
                                <Input.Password
                                    size="large"
                                    prefix={<LockOutlined />}
                                    placeholder="确认密码"
                                    value={confirmPasswordValue}
                                    onChange={(e) => setConfirmPasswordValue(e.target.value)}
                                    style={{ width: 'calc(100% - 28px)' }}
                                />
                                <div style={{
                                    width: '20px',
                                    display: 'flex',
                                    justifyContent: 'center',
                                    alignItems: 'center'
                                }}>
                                    {getConfirmPasswordValidationIcon()}
                                </div>
                            </div>
                        </Form.Item>
                        {error && <Alert message={error} type="error" showIcon style={{ marginBottom: 16, width: '100%' }} />}
                        <Button
                            type="primary"
                            size="large"
                            htmlType="submit"
                            loading={signUpLoading}
                            style={{ marginTop: '10px' }}
                        >
                            {signUpLoading ? '注册中...' : '注 册'}
                        </Button>
                    </Form>
                </div>
                <div className="form-container sign-in-container">
                    <Form form={signInForm} onFinish={handleSignIn} className="auth-form">
                        <Title level={2}>登录系统</Title>
                        <div style={{ margin: '15px 0' }}>
                            {/* Placeholder for social icons */}
                        </div>
                        <Form.Item name="username" rules={[{ required: true, message: '请输入用户名!' }]}>
                            <Input size="large" prefix={<UserOutlined />} placeholder="用户名" />
                        </Form.Item>
                        <Form.Item name="password" rules={[{ required: true, message: '请输入密码!' }]}>
                            <Input.Password size="large" prefix={<LockOutlined />} placeholder="密码" />
                        </Form.Item>
                        {error && <Alert message={error} type="error" showIcon style={{ marginBottom: 24, width: '100%' }} />}
                        <Button
                            type="primary"
                            size="large"
                            htmlType="submit"
                            loading={signInLoading}
                            style={{ marginTop: '10px' }}
                        >
                            {signInLoading ? '登录中...' : '登 录'}
                        </Button>
                        <Link to="/admin/login" className="admin-link">
                            管理员登录
                        </Link>
                    </Form>
                </div>
                <div className="overlay-container">
                    <div className="overlay">
                        <div className="overlay-panel overlay-left">
                            <Title level={1}>欢迎回来!</Title>
                            <Paragraph>已经拥有账户？请直接登录以管理您的门禁权限。</Paragraph>
                            <Button className="ghost-button" size="large" onClick={() => setIsSignUp(false)}>
                                去登录
                            </Button>
                        </div>
                        <div className="overlay-panel overlay-right">
                            <Title level={1}>加入我们!</Title>
                            <Paragraph>还没有账户？立即注册，开启您的智能门禁体验。</Paragraph>
                            <Button className="ghost-button" size="large" onClick={() => setIsSignUp(true)}>
                                去注册
                            </Button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
};

export default AuthPage;